package Servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import DAO.DatabaseDAO;
import User.User;
import User.Users;

/**
 * Servlet implementation class RegistrationServlet
 */
@WebServlet("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistrationServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext ctx = getServletContext();
		HttpSession session = request.getSession();
		
		PrintWriter out = response.getWriter(); 
		
		String username = request.getParameter("username");
		String client = request.getParameter("client");
		if(client==null){
			client="web";
		}
		
		Users users = (Users) session.getAttribute("users");
		if(users==null){
			users =	new Users(ctx.getRealPath(""));
		}
		
		if(username!=null){
			for(User u : users.getUsers()){
				if(username.equals(u.getUsername())){
					session.setAttribute("user", "vecPostoji");
					
					if(client.equals("CommandPrompt")){
						out.println("Korisnicko ime vec postoji"); 
						out.close();
					} else {
						RequestDispatcher disp = getServletContext().getRequestDispatcher("/registracija.faces");
						disp.forward(request, response);
					}

					return;
				}
			}
			

			DatabaseDAO dao = DatabaseDAO.getInstance();
			dao.save(username, ctx.getRealPath("")+"/users.txt");
			
			if(client.equals("CommandPrompt")){
				out.println("Uspesno ste se registrovali"); 
				out.close();
			} else {
				RequestDispatcher disp = getServletContext().getRequestDispatcher("/LogInServlet");
				disp.forward(request, response);
			}

			return;
		} else {
			session.setAttribute("user", null);
			
			if(client.equals("CommandPrompt")){
				out.println("GRESKA"); 
				out.close();
			} else {
				RequestDispatcher disp = getServletContext().getRequestDispatcher("/registracija.faces");
				disp.forward(request, response);
			}

			return;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
